package com.jch.integration.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ClientHandler extends ChannelInboundHandlerAdapter {

    private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(format.format(new Date()) + " 客户端 " + ctx.channel().localAddress().toString() + " 连接到服务器: " + ctx.channel().remoteAddress().toString());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("断开连接：" + ctx.channel().localAddress().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(format.format(new Date()) + " 客户端收到消息：" + msg);
        ctx.writeAndFlush("客户端成功收到消息！\r\n");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息：" + cause.getMessage());
    }
}
